import 'package:flutter/material.dart';
import 'package:hive_flutter/hive_flutter.dart';
import 'package:ichinesereader/controller/books.dart';
import 'package:ichinesereader/controller/evaluation.dart';
import 'package:ichinesereader/controller/knowledgeword.dart';
import 'package:ichinesereader/models/book/BookArguments.dart';
import 'package:ichinesereader/models/book/BookItem.dart';
import 'package:ichinesereader/pages/book/bookKnowledges.dart';
// import 'package:ichinesereader/pages/book/bookQuickReview.dart';
import 'package:ichinesereader/pages/word/WordCardQuiz.dart';
import 'package:ichinesereader/utils/helper.dart';
import 'package:ichinesereader/constants.dart';
import 'package:get/get.dart';
import 'package:ichinesereader/controller/cache.dart';
import 'package:just_the_tooltip/just_the_tooltip.dart';
import 'package:reactive_forms/reactive_forms.dart';
import 'package:universal_html/html.dart' as uHtml;
import '../../controller/assessments.dart';
import 'package:ichinesereader/pages/book/bookfullText.dart';
import '../../pages/book/bookQuizReviewer.dart';
import '../../pages/teacher/evaluationRecordReview.dart';
import '../../themes/appTheme.dart';

class BookGridWithCheckBoxTeaching extends StatefulWidget {
  BookGridWithCheckBoxTeaching(
      {Key? key, required this.books, required this.readingType, this.form})
      : super(key: key);

  final List<BookItem> books;
  final NanhaiBookReadingTypes readingType;
  final FormGroup? form;

  @override
  State<BookGridWithCheckBoxTeaching> createState() =>
      _BookGridWithCheckBoxTeachingState();
}

class _BookGridWithCheckBoxTeachingState
    extends State<BookGridWithCheckBoxTeaching> {
  final BooksController _bookcontroller = Get.find();
  final EvaluationController _evaluationController = Get.find();
  late ScrollController _scrollController;
  final box = Hive.box('appconfig');

  @override
  void initState() {
    _scrollController = ScrollController();
    _scrollController.addListener(_scrollListener);
    super.initState();
  }

  @override
  void dispose() {
    _scrollController.dispose();
    _bookcontroller.setCurrentPage(0);

    super.dispose();
  }

  _scrollListener() {
    if (_scrollController.offset >=
            _scrollController.position.maxScrollExtent &&
        !_scrollController.position.outOfRange) {
      if (widget.readingType == NanhaiBookReadingTypes.library &&
          widget.books.length >= Constants.pageLimit) {
        _bookcontroller.fetchMoreOpenReadingItems();
      } else if (widget.readingType == NanhaiBookReadingTypes.favorite &&
          widget.books.length >= Constants.pageLimit) {
        _bookcontroller.fetchMoreMyFavoriteReadingItemsByFolder();
      } else if (widget.readingType == NanhaiBookReadingTypes.theme &&
          // for core material part
          widget.books.length >= Constants.pageLimit) {
        _bookcontroller.fetchMoreProgramThemeBookItems();
      }
    }
  }

  @override
  Widget build(BuildContext context) {
    bool isTeacher = box.get(CacheManagerKey['nanhairole'].toString()) ==
        Constants.NanhaiRole_Teacher;
    return GridView.builder(
        padding: EdgeInsets.zero,
        controller: _scrollController,
        gridDelegate: const SliverGridDelegateWithMaxCrossAxisExtent(
            maxCrossAxisExtent: 240,
            childAspectRatio: 156 / 200,
            crossAxisSpacing: 9.0,
            mainAxisSpacing: 9.0),
        itemCount: widget.books.length,
        itemBuilder: (BuildContext ctx, index) {
          String bid = widget.books[index].bookId ?? '';
          String btitle = widget.books[index].bookTitle ?? '';
          String bcode = widget.books[index].bookCode ?? '';
          String bimage = widget.books[index].bookImageLink ?? '';
          String color = widget.books[index].color ?? '';
          String bookLevel = widget.books[index].bookLevel ?? '';
          String desc = widget.books[index].description ?? '';
          bool quizAvailable = widget.books[index].quizAvailable ?? false;
          bool inFolder = widget.books[index].inFolder ?? false;
          bool ifAssigned = widget.books[index].ifAssigned ?? false;
          return Container(
            decoration: BoxDecoration(
              color: Get.isDarkMode
                  ? AppTheme.colors.darkTheme2
                  : Colors.white.withOpacity(0.45),
              borderRadius: BorderRadius.circular(3.0),
            ),
            padding: EdgeInsets.fromLTRB(12.0, 12.0, 6.0, 6.0),
            alignment: Alignment.center,
            //这个margin会在上面多出空白的地方，尤其是ipad apps比较明显
            //margin: const EdgeInsets.only(top: 15.0),
            child: Row(
              mainAxisAlignment: MainAxisAlignment.start,
              crossAxisAlignment: CrossAxisAlignment.start,
              children: [
                Expanded(
                  //padding: const EdgeInsets.all(8.0),
                  child: Column(
                    crossAxisAlignment: CrossAxisAlignment.stretch,
                    children: <Widget>[
                      Expanded(
                        child: new MouseRegion(
                            cursor: SystemMouseCursors.click,
                            child: GestureDetector(
                              onTap: () {
                                if (bid == '') return;

                                if (GetPlatform.isWeb) {
                                  uHtml.window.localStorage['bookBasePath'] =
                                      'https://resources.ichinesereader.com/books/$bcode/assets';
                                  uHtml.window.localStorage['bookCode'] = bcode;
                                  uHtml.window.localStorage['bookID'] = bid;
                                }
                                if (GetPlatform.isDesktop ||
                                    GetPlatform.isMacOS ||
                                    GetPlatform.isWeb) {
                                  launchInWebViewWithJavaScript(
                                      '${Constants.BaseURL}icr/student/book/$bid');
                                } else {
                                  String viewMode =
                                      this.widget.books[index].viewMode ??
                                          'LANDSCAPE';
                                  box.put(
                                      CacheManagerKey['_viewMode'].toString(),
                                      viewMode);
                                  bool quizAvailable =
                                      this.widget.books[index].quizAvailable ??
                                          false;
                                  box.put(
                                      CacheManagerKey['_quizAvailable']
                                          .toString(),
                                      quizAvailable);
                                  bool readComplete =
                                      this.widget.books[index].readComplete ??
                                          false;
                                  box.put(
                                      CacheManagerKey['_readComplete']
                                          .toString(),
                                      readComplete);
                                  Navigator.pushNamed(context, '/student/book',
                                      arguments: BookArguments(
                                          bid,
                                          bcode,
                                          btitle,
                                          null,
                                          this.widget.readingType,
                                          null));
                                }
                              },
                              child: JustTheTooltip(
                                backgroundColor: Get.isDarkMode
                                    ? Get.theme.primaryColorDark
                                    : Get.theme.primaryColorLight,
                                preferredDirection: AxisDirection.right,
                                elevation: 4.0,
                                content: Container(
                                  padding: EdgeInsets.all(12.0),
                                  width: 150,
                                  child: Text(
                                    desc != '' ? desc : btitle,
                                    softWrap: true,
                                    maxLines: 10,
                                    style: TextStyle(
                                      letterSpacing: 0.6,
                                      fontSize: 15,
                                      color: Get.isDarkMode
                                          ? Colors.black
                                          : Colors.black87,
                                    ),
                                    overflow: TextOverflow.fade,
                                  ),
                                ),
                                child: Image.network(
                                  bimage,
                                  height: 200.0,
                                  width: 156,
                                  fit: BoxFit.cover,
                                  errorBuilder: (context, error, stackTrace) {
                                    return Image.asset(
                                        'assets/images/imagenotavailable.png',
                                        height: 200.0,
                                        width: 156,
                                        fit: BoxFit.cover);
                                  },
                                ),
                              ),
                            )),
                      ),
                      Container(
                        height: 45.0,
                        margin: const EdgeInsets.only(top: 12.0),
                        child: new MouseRegion(
                            cursor: SystemMouseCursors.click,
                            child: GestureDetector(
                                onTap: () {
                                  if (GetPlatform.isDesktop ||
                                      GetPlatform.isMacOS ||
                                      GetPlatform.isWeb) {
                                    launchInWebViewWithJavaScript(
                                        '${Constants.BaseURL}icr/student/book/$bid');
                                  } else {
                                    String viewMode =
                                        this.widget.books[index].viewMode ??
                                            'LANDSCAPE';
                                    box.put(
                                        CacheManagerKey['_viewMode'].toString(),
                                        viewMode);
                                    bool quizAvailable = this
                                            .widget
                                            .books[index]
                                            .quizAvailable ??
                                        false;
                                    box.put(
                                        CacheManagerKey['_quizAvailable']
                                            .toString(),
                                        quizAvailable);
                                    bool readComplete =
                                        this.widget.books[index].readComplete ??
                                            false;
                                    box.put(
                                        CacheManagerKey['_readComplete']
                                            .toString(),
                                        readComplete);
                                    Navigator.pushNamed(
                                        context, '/student/book',
                                        arguments: BookArguments(
                                            bid,
                                            bcode,
                                            btitle,
                                            null,
                                            this.widget.readingType,
                                            null));
                                  }
                                },
                                child: Row(
                                  mainAxisAlignment: MainAxisAlignment.start,
                                  crossAxisAlignment: CrossAxisAlignment.start,
                                  children: [
                                    Container(
                                      margin: EdgeInsets.only(right: 3.0),
                                      padding: EdgeInsets.symmetric(
                                          horizontal: 4.5, vertical: 1.0),
                                      decoration: BoxDecoration(
                                        color: hexStringToHexInt(color),
                                        borderRadius:
                                            BorderRadius.circular(12.0),
                                      ),
                                      child: Text(
                                        bookLevel != '0'
                                            ? ' L $bookLevel '
                                            : 'N/A',
                                        style: TextStyle(
                                          fontFamily: 'Montserrat',
                                          fontSize: 13,
                                          color: Colors.white,
                                        ),
                                      ),
                                    ),
                                    Flexible(
                                      child: Text('$btitle',
                                          maxLines: 2,
                                          overflow: TextOverflow.fade,
                                          style: TextStyle(
                                            color: Get.isDarkMode
                                                ? Get.theme.primaryColorDark
                                                : Colors.black,
                                            fontSize: 14.0,
                                            fontFamily: 'Noto Sans SC',
                                          )),
                                    )
                                  ],
                                ))),
                      ),
                    ],
                  ),
                ),
                Container(
                  margin: const EdgeInsets.symmetric(horizontal: 6.0),

                  ///右侧icons/////
                  child: Column(
                    mainAxisAlignment: MainAxisAlignment.start,
                    children: [
                      SizedBox(
                        width: 24,
                        height: 24,
                        child: Checkbox(
                            activeColor: Get.isDarkMode
                                ? AppTheme.colors.primaryLight
                                : Get.theme.primaryColorDark,
                            checkColor:
                                Get.isDarkMode ? Colors.black : Colors.white,
                            value: widget.books[index].selected ?? false,
                            onChanged: (value) {
                              if (widget.readingType ==
                                  NanhaiBookReadingTypes.evaluation) {
                                if (value == true) {
                                  _evaluationController.addToSelectedBookItems(
                                      widget.books[index],
                                      this.widget.readingType);
                                } else {
                                  _evaluationController
                                      .removeFromSelectedBookItems(
                                          widget.books[index],
                                          this.widget.readingType);
                                }
                              } else {
                                if (value == true) {
                                  _bookcontroller.addToSelectedBookItems(
                                      widget.books[index],
                                      this.widget.readingType);
                                } else {
                                  _bookcontroller.removeFromSelectedBookItems(
                                      widget.books[index],
                                      this.widget.readingType);
                                }
                                if (widget.form != null) {
                                  widget.form
                                          ?.control('review.totalbooks')
                                          .value =
                                      _bookcontroller
                                          .selectedLibraryReadingBookItems
                                          .length;
                                  widget.form
                                          ?.control('review.completerequired')
                                          .value =
                                      _bookcontroller
                                          .selectedLibraryReadingBookItems
                                          .length;
                                }
                              }
                              widget.books[index].selected = value;
                            }),
                      ),
                      const SizedBox(height: 8),
                      // Padding(
                      //   padding: const EdgeInsets.only(top: 10.0),
                      // ),
                      Icon(
                        Icons.book,
                        size: 24.0,
                        color: ifAssigned
                            ? AppTheme.colors.orangeBtn
                            : Get.isDarkMode
                                ? Get.theme.primaryColorDark
                                : Colors.white,
                      ),
                      const SizedBox(height: 8),
                      MouseRegion(
                          cursor: SystemMouseCursors.click,
                          child: GestureDetector(
                            child: Icon(
                              Icons.translate_outlined,
                              size: 24.0,
                              color: Get.isDarkMode
                                  ? Get.theme.primaryColorDark
                                  : Colors.white,
                            ),
                            onTap: () {
                              if (bcode.isNotEmpty) {
                                Get.to(() => BookFullTextViewer(
                                      bookCode: bcode,
                                      simplified: true,
                                      bookTitle: btitle,
                                    ));
                              }
                            },
                          )),
                      Visibility(
                        visible: true,
                        child: const SizedBox(height: 8),
                      ),
                      Visibility(
                          visible: true,
                          child: MouseRegion(
                              cursor: SystemMouseCursors.click,
                              child: GestureDetector(
                                child: Icon(Icons.wordpress_rounded,
                                    color: Get.isDarkMode
                                        ? Get.theme.primaryColorDark
                                        : Colors.white,
                                    size: 24.0),
                                onTap: () {
                                  final KnowledgeWordsController
                                      _wordcontroller =
                                      Get.put(KnowledgeWordsController());
                                  _wordcontroller
                                      .fetchWordQuiz(bcode, null)
                                      .then((data) {
                                    if (data.status == 1000 &&
                                        data.result != null) {
                                      _wordcontroller.bookCode = bcode;
                                      Get.to(() => WordCardQuiz());
                                    } else {
                                      Get.delete<KnowledgeWordsController>();
                                      showSnackMsg(
                                          'Word quiz data coming soon');
                                      // Get.snackbar('Message'.tr,
                                      //     'Word quiz data coming soon'.tr,
                                      //     backgroundColor:
                                      //         Theme.of(context).primaryColor,
                                      //     colorText: Theme.of(context)
                                      //         .primaryColorLight,
                                      //     snackPosition: SnackPosition.BOTTOM);
                                    }
                                  });
                                  //}
                                },
                              ))),
                      Visibility(
                        visible: this.widget.readingType ==
                            NanhaiBookReadingTypes.evaluation,
                        child: const SizedBox(height: 8),
                      ),
                      Visibility(
                          visible: this.widget.readingType ==
                              NanhaiBookReadingTypes.evaluation,
                          child: MouseRegion(
                              cursor: SystemMouseCursors.click,
                              child: GestureDetector(
                                onTap: () {
                                  if (bcode.isNotEmpty) {
                                    AssessmentsController _controller =
                                        Get.find();
                                    _controller
                                        .fetchQuestionGroupByBookCode(bcode);
                                    Get.to(() => EvaluationRecordReviewPage(),
                                        arguments: {
                                          'title': btitle,
                                          'status': 'NEW'
                                        });
                                  }
                                },
                                child: Icon(
                                  Icons.quiz_outlined,
                                  size: 24.0,
                                  color: Get.isDarkMode
                                      ? Get.theme.primaryColorDark
                                      : Colors.white,
                                ),
                              ))),
                      Visibility(
                        visible: this.widget.readingType !=
                                NanhaiBookReadingTypes.evaluation &&
                            quizAvailable == true,
                        child: const SizedBox(height: 8),
                      ),
                      Visibility(
                          visible: this.widget.readingType !=
                                  NanhaiBookReadingTypes.evaluation &&
                              quizAvailable == true,
                          child: MouseRegion(
                              cursor: SystemMouseCursors.click,
                              child: GestureDetector(
                                onTap: () {
                                  if (bcode.isNotEmpty) {
                                    Get.to(() => BookQuizReviewer(
                                          bookId: bid,
                                          bookTitle: btitle,
                                        ));
                                  }
                                },
                                child: Icon(
                                  Icons.quiz_outlined,
                                  size: 24.0,
                                  color: Get.isDarkMode
                                      ? Get.theme.primaryColorDark
                                      : Colors.white,
                                ),
                              ))),
                      Visibility(
                        visible: this.widget.readingType ==
                                NanhaiBookReadingTypes.evaluation &&
                            isTeacher,
                        child: const SizedBox(height: 8),
                      ),
                      Visibility(
                          visible: this.widget.readingType ==
                                  NanhaiBookReadingTypes.evaluation &&
                              isTeacher,
                          child: MouseRegion(
                            cursor: SystemMouseCursors.click,
                            child: GestureDetector(
                              child: Icon(
                                //Icons.text_fields_rounded,
                                Icons.g_translate_rounded,
                                size: 24.0,
                                color: Get.isDarkMode
                                    ? Get.theme.primaryColorDark
                                    : Colors.white,
                              ),
                              onTap: () {
                                Get.to(() => BookKnowledgesViewer(
                                      bookItem: this.widget.books[index],
                                    ));
                              },
                            ),
                          )),
                      Visibility(
                        visible: this.widget.readingType !=
                                NanhaiBookReadingTypes.evaluation &&
                            isTeacher,
                        child: const SizedBox(height: 8),
                      ),
                      // Visibility(
                      //     visible: this.widget.readingType !=
                      //             NanhaiBookReadingTypes.evaluation &&
                      //         isTeacher,
                      //     child: MouseRegion(
                      //         cursor: SystemMouseCursors.click,
                      //         child: GestureDetector(
                      //           child: Icon(Icons.remove_red_eye_sharp,
                      //               color: Colors.white, size: 21.0),
                      //           onTap: () {
                      //             //assessment controller去掉暂时有些困难，先使用permenent的方式
                      //             final AssessmentsController
                      //                 _assessmentsController = Get.find();
                      //             //print(currentBook.bookCode);
                      //             _assessmentsController
                      //                 .getQuickReviewQuestionGroupByBookCode(
                      //                     '$bcode-review')
                      //                 .then((data) {
                      //               if (data != null && data.list != null) {
                      //                 Get.to(() => BookQuickReview(
                      //                       bookItem: this.widget.books[index],
                      //                     ));
                      //               } else {
                      //                 showSnackMsg(
                      //                     'Book quick review data coming soon');
                      //                 // Get.snackbar(
                      //                 //     'Message'.tr,
                      //                 //     'Book quick review data coming soon'
                      //                 //         .tr,
                      //                 //     backgroundColor:
                      //                 //         Theme.of(context).primaryColor,
                      //                 //     colorText: Theme.of(context)
                      //                 //         .primaryColorLight,
                      //                 //     snackPosition: SnackPosition.BOTTOM);
                      //               }
                      //             });
                      //           },
                      //         ))),
                      Visibility(
                        child: const SizedBox(height: 8),
                        visible: this.widget.readingType !=
                            NanhaiBookReadingTypes.evaluation,
                      ),
                      Visibility(
                        child: Icon(Icons.favorite_border_rounded,
                            size: 24.0,
                            color: inFolder
                                ? AppTheme.colors.orangeBtn
                                : Colors.white),
                        visible: this.widget.readingType !=
                            NanhaiBookReadingTypes.evaluation,
                      ),
                    ],
                  ),
                )
              ],
            ),
          );
        });
  }
}
